<template>
  <div class="invite-page">
    <div class="invite-content">
      <div class="invite-link-section">
        <div class="section-label">{{ t("invite_linkLabel") }}</div>
        <div class="invite-link">{{ inviteLink }}</div>
        <div class="copy-icon" @click="copyInviteLink">
          <van-icon name="link-o" size="20" color="#f6e0ca" />
        </div>
      </div>

      <div class="qr-code-section">
        <div class="qr-code-container">
          <img :src="qrCodeWithLogo" alt="QR Code" class="qr-code" />
        </div>
      </div>

      <div class="action-button" @click="saveQrCode">
        <van-icon name="photo-o" size="18" style="margin-right: 5px" />
        {{ t("invite_saveQr") }}
      </div>

      <div
        class="invite-reward-card"
        v-if="Number(userInfo.rigdays)  <= Number(inviteInfo.frastCycle)"
      >
        <div class="reward-header">
          <span class="reward-icon"></span>
          <span class="reward-title">{{ t("invite_rewardTitle") }}</span>
        </div>

        <div class="reward-progress">
          <div class="progress-text">
            {{
              t("invite_progress", {
                count: inviteInfo.frasePeople,
                daycount: inviteInfo.frastCycle,
              })
            }}
          </div>
          <div class="progress-bar-container">
            <div
              class="progress-bar"
              :style="{ width: progressPercentage + '%' }"
            ></div>
          </div>
          <div class="progress-amount">
            COP{{ formatNumber(inviteInfo.frastReward) }}
          </div>
        </div>
      </div>

      <div class="section-divider">
        <div class="divider-label">{{ t("invite_tips") }}</div>
      </div>

      <div class="tips-section">
        <div class="tip-item">
          <div class="tip-marker"></div>
          <div class="tip-content">
            {{ t("invite_copyTip") }}
          </div>
        </div>

        <div class="tip-item">
          <div class="tip-marker"></div>
          <div class="tip-content">
            {{ t("invite_teamTip") }}
          </div>
        </div>

        <div class="tip-item">
          <div class="tip-marker"></div>
          <div class="tip-content">
            {{ t("invite_incomeTip") }}

            {{
              (parseFloat(inviteInfo.teamGasOne || "0") * 100).toFixed(2) +
              "%" +
              " 、" +
              (parseFloat(inviteInfo.teamGasTwo || "0") * 100).toFixed(2) +
              "%"
            }}
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
// 导入所需的依赖
import { useUserStore } from "@/stores";
import QRCode from "qrcode";
import { showToast } from "vant/es";
import { computed, onMounted, ref } from "vue";
import { useRouter } from "vue-router";
import { withdrawalTips } from "@/api/user";
import { formatNumber } from "@/utils/public";
import { number } from "echarts";
// 初始化数据
const router = useRouter();
const userStore = useUserStore();
const inviteCode = ref("obt1spus");
const inviteLink = computed(
  () =>
    window.location.origin +
    "/#/register?code=" +
    userStore.userInfo?.recomcode,
);
const invitedCount = ref(3);
const targetCount = ref(7);
const qrCodeWithLogo = ref("");
const inviteInfo = ref("");

// 用户信息从store中获取
const userInfo = computed(() => userStore.userInfo || {});

const { t } = useI18n();
// 计算邀请进度百分比
const progressPercentage = computed(() => {
  return Math.min(
    (userInfo.value.un_direct_people / targetCount.value) * 100,
    100,
  );
});

// 生命周期钩子
onMounted(() => {
  // 获取邀请信息
  getInviteInfo();
  // 生成二维码
  generateQRCode();
  getwithdrawalTips();
});

// 方法定义
function getInviteInfo() {
  // 模拟获取邀请码和链接
  // 实际应用中，这里会从API获取数据
  console.log("invite");
}

const getwithdrawalTips = async () => {
  try {
    const res = await withdrawalTips();
    if (res.code === 200) {
      inviteInfo.value = res.data;
      targetCount.value = res.data.frasePeople;
    } else {
      showToast(res.msg || t("user-coupon_noData"));
    }
  } catch (e) {
    showToast(t("products_networkError"));
  } finally {
  }
};

// 生成带有logo的二维码
async function generateQRCode() {
  try {
    // 先生成普通的二维码
    const qrCodeDataUrl = await QRCode.toDataURL(inviteLink.value, {
      errorCorrectionLevel: "H", // 高纠错级别，以便放置logo
      margin: 1,
      width: 200,
      color: {
        dark: "#000000",
        light: "#FFFFFF",
      },
    });

    // 创建画布在客户端合成logo
    const canvas = document.createElement("canvas");
    const ctx = canvas.getContext("2d");
    const size = 200;
    canvas.width = size;
    canvas.height = size;

    // 绘制二维码背景
    const qrImage = new Image();
    qrImage.src = qrCodeDataUrl;

    // 等待图片加载完成
    qrImage.onload = () => {
      // 绘制二维码
      ctx.drawImage(qrImage, 0, 0, size, size);

      // 加载logo
      const logoImage = new Image();
      logoImage.src = new URL(
        "@/assets/images/logo_icon.png",
        import.meta.url,
      ).href;

      // 等待logo加载完成
      logoImage.onload = () => {
        // 计算logo大小和位置
        const logoSize = 80; // 固定80*80像素的logo
        const logoX = (size - logoSize) / 2;
        const logoY = (size - logoSize) / 2;

        // 绘制白色背景
        ctx.fillStyle = "#FFFFFF";
        ctx.beginPath();
        ctx.arc(
          logoX + logoSize / 2,
          logoY + logoSize / 2,
          logoSize / 2 + 2,
          0,
          Math.PI * 2,
        );
        ctx.fill();

        // 绘制logo
        ctx.drawImage(logoImage, logoX, logoY, logoSize, logoSize);

        // 转换为dataURL
        qrCodeWithLogo.value = canvas.toDataURL("image/png");
      };

      // logo加载失败时使用普通二维码
      logoImage.onerror = () => {
        qrCodeWithLogo.value = qrCodeDataUrl;
        console.error("err");
      };
    };

    // 二维码加载失败时的处理
    qrImage.onerror = () => {
      console.error("qr");
    };
  } catch (error) {
    console.error("err:", error);
  }
}

// function copyInviteLink() {
//   // 复制邀请链接到剪贴板
//   try {
//     navigator.clipboard.writeText(inviteLink.value)
//     showToast(t("invite_copySuccess"))
//   } catch (err) {
//     console.error('Gagal menyalin:', err)
//     showToast(t("invite_copyFail"))
//   }
//   navigator.clipboard.writeText(inviteLink.value)
//     .then(() => {
//       showToast('复制成功')
//     })
//     .catch(() => {
//       showToast('复制失败，请手动复制')
//     })
// }
const copyInviteLink = () => {
  if (navigator.clipboard && navigator.clipboard.writeText) {
    navigator.clipboard
      .writeText(inviteLink.value)
      .then(() => showToast(t("invite_copySuccess")))
      .catch(() => fallbackCopy());
  } else {
    fallbackCopy();
  }
};

function fallbackCopy() {
  const input = document.createElement("input");
  input.value = inviteLink.value;
  document.body.appendChild(input);
  input.select();
  document.execCommand("copy");
  document.body.removeChild(input);
  showToast(t("invite_copySuccess"));
}

function saveQrCode() {
  if (!qrCodeWithLogo.value) return;
  const a = document.createElement("a");
  a.href = qrCodeWithLogo.value;
  a.download = "invite_qrcode.png";
  a.click();
}
</script>

<style lang="less" scoped>
.invite-page {
  min-height: 100vh;
  background: url("@/assets/images/user/Topbg.png") no-repeat center center;
  background-size: cover;
  color: #f6e0ca;
  padding-bottom: 30px;
}

.page-header {
  display: flex;
  align-items: center;
  padding: 15px;
  position: relative;

  .back-button {
    position: absolute;
    left: 15px;
    width: 20px;
    height: 20px;
    cursor: pointer;

    img {
      width: 100%;
      height: 100%;
    }
  }

  .page-title {
    flex: 1;
    text-align: center;
    font-size: 16px;
    font-weight: 500;
  }
}

.invite-content {
  padding: 0 20px;
}

.invite-link-section {
  margin-top: 20px;
  position: relative;
  background: linear-gradient(
    180deg,
    rgba(254, 242, 230, 0) 4%,
    rgba(254, 237, 221, 0.1) 63%
  );
  .section-label {
    font-size: 14px;
    margin-bottom: 10px;
  }

  .invite-link {
    font-size: 13px;
    background-color: rgba(30, 27, 26, 0.6);
    border-radius: 8px;
    padding: 15px;
    word-break: break-all;
    padding-right: 40px;
  }

  .copy-icon {
    position: absolute;
    right: 15px;
    bottom: 15px;
    width: 20px;
    height: 20px;
    cursor: pointer;

    img {
      width: 100%;
      height: 100%;
    }
  }
}

.qr-code-section {
  margin: 20px 0;
  display: flex;
  justify-content: center;

  .qr-code-container {
    background-color: white;
    padding: 10px;
    border-radius: 8px;
    width: 200px;
    height: 200px;
    display: flex;
    align-items: center;
    justify-content: center;

    .qr-code {
      width: 100%;
      height: 100%;
      object-fit: contain;
    }
  }
}

.action-button {
  background-color: #f6e0ca;
  color: #332b27;
  height: 45px;
  display: flex;
  justify-content: center;
  align-items: center;
  border-radius: 8px;
  font-size: 16px;
  font-weight: bold;
  margin: 20px 0;
  cursor: pointer;

  &:active {
    opacity: 0.9;
  }
}

.invite-reward-card {
  background-color: rgba(30, 27, 26, 0.6);
  border-radius: 10px;
  padding: 15px;
  margin: 20px 0;

  .reward-header {
    display: flex;
    align-items: center;
    margin-bottom: 15px;

    .reward-icon {
      display: inline-block;
      width: 4px;
      height: 18px;
      background-color: #f8d996;
      color: #332b27;
      text-align: center;
      line-height: 18px;
      font-weight: bold;
      margin-right: 10px;
    }

    .reward-title {
      font-size: 14px;
      font-weight: 500;
    }
  }

  .reward-progress {
    .progress-text {
      font-size: 13px;
      margin-bottom: 10px;
      color: rgba(246, 224, 202, 0.8);
    }

    .progress-bar-container {
      height: 6px;
      background-color: rgba(255, 255, 255, 0.1);
      border-radius: 3px;
      margin-bottom: 5px;

      .progress-bar {
        height: 100%;
        background-color: #f6e0ca;
        border-radius: 3px;
      }
    }

    .progress-amount {
      text-align: right;
      font-size: 12px;
    }
  }
}

.section-divider {
  position: relative;
  height: 20px;
  margin: 30px 0 20px;

  &::before {
    content: "";
    position: absolute;
    left: 0;
    top: 50%;
    width: 100%;
    height: 1px;
    background-color: rgba(255, 255, 255, 0.1);
  }

  .divider-label {
    position: absolute;
    left: 0;
    top: 0;
    padding-right: 15px;
    background-color: #221a18;
    font-size: 16px;
    font-weight: 500;
  }
}

.tips-section {
  .tip-item {
    display: flex;
    margin-bottom: 15px;

    .tip-marker {
      width: 8px;
      height: 8px;
      border-radius: 50%;
      background-color: #fff;
      margin-top: 6px;
      margin-right: 10px;
      flex-shrink: 0;
    }

    .tip-content {
      font-size: 13px;
      line-height: 1.5;
      color: rgba(246, 224, 202, 0.8);
    }
  }
}
</style>
